from django.http import HttpResponse,JsonResponse
from index.models import User,Article
import json
from django.core import serializers
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator


from django.views import View
import json,time,datetime

 
class MyJSONEncoder(json.JSONEncoder):
    def default(self, field):
        if isinstance(field, datetime.datetime):
            return field.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(field, datetime.date):
            return field.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, field)

@method_decorator(csrf_exempt,name="dispatch")
class ArticleList(View):
    def init(self):
        print("hello")
    def get(self,request):
        self.init()
        return JsonResponse(data={"a":11})
    def post(self,request):
        pass
#新增文章
# post必须装饰才能收到数据
@csrf_exempt
def add_article(request):
    if request.method == "POST":
        # loads(request.body.decode('utf-8'))
        req = json.loads(request.body)
        print (req)
        key_flag = True # 验证参数
        #判断请求体是否正确
        if key_flag:
            title = req["title"]
            content = req["content"]
            #title返回的是一个list
            title_exist = Article.objects.filter(title=title)
            #判断是否存在同名title
            if len(title_exist) != 0:
                return JsonResponse({"status":"BS.400","msg":"title aleady exist,fail to publish."})

            '''插入数据'''
            add_art = Article(title=title,content=content,status= req["status"])
            add_art.save()
            return JsonResponse({"status":"BS.200","msg":"publish article sucess."})
        else:
            return  JsonResponse({"status":"BS.400","message":"please check param."})
    #查询所有文章和状态
    if request.method == "GET":
        articles = {}
        query_art = list(Article.objects.all().values())
        print(query_art)
        # for title in query_art:
        #     articles[title.title] = title.status
        # qs_json = serializers.serialize('json', query_art)
        # return HttpResponse(qs_json, content_type='application/json')
        return  JsonResponse({"status":"BS.400","data":query_art,"message":"please check param."},encoder=MyJSONEncoder)

def modify_article(request,art_id):
    if request.method == "POST":
        req = json.loads(request.body)
        try:
            art = Article.objects.get(id=art_id)
            key_flag = req.get("title") and req.get("content") and len(req)==2
            if key_flag:
                title = req["title"]
                content = req["content"]
                title_exist = Article.objects.filter(title=title)
                if len(title_exist) > 1:
                    return JsonResponse({"status":"BS.400","msg":"title aleady exist."})
                '''更新数据'''
                old_art = Article.objects.get(id=art_id)
                old_art.title = title
                old_art.content = content
                old_art.save()
                return JsonResponse({"status":"BS.200","msg":"modify article sucess."})
        except Article.DoesNotExist:
            return  JsonResponse({"status":"BS.300","msg":"article is not exists,fail to modify."})

            #删除文章
    if request.method == "DELETE":
        try:
            art = Article.objects.get(id=art_id)
            art_id = art.id
            art.delete()
            return JsonResponse({"status":"BS.200","msg":"delete article sucess."})
        except Article.DoesNotExist:
            return JsonResponse({"status":"BS.300","msg":"article is not exists,fail to delete."})
@csrf_exempt
def login_views(request):
    from django.contrib.auth import login,authenticate
    print(request.POST)
    
    username=request.POST.get("username", "hello")
    password=request.POST.get("password","")
    print(username,password)
    #调用 authenticate对user进行认证
    user=authenticate(username=username,password=password)
    print(user)
    if user:
        #调用auth的login api
        login(request,user)
        return JsonResponse({"status":"BS.200","msg":"sucess."})
    else:
        return JsonResponse({"status":"BS.200","msg":"error."})
 